﻿using System;
using System.Collections.Generic;
using System.Text;
using ESPlus.Rapid;
using GG.Core;
using ESPlus.Serialization;

namespace GG.Server
{
    /// <summary>
    /// 离线消息控制器 V3.2
    /// </summary>
    internal class OfflineMessageController
    {
        private IRapidServerEngine rapidServerEngine;
        private VirtualDB virtualDB;
        public OfflineMessageController(IRapidServerEngine engine ,VirtualDB db)
        {
            this.rapidServerEngine = engine;
            this.virtualDB = db;
            this.rapidServerEngine.CustomizeController.TransmitFailed += new ESBasic.CbGeneric<ESPlus.Application.Information>(CustomizeController_TransmitFailed);
          }        

        //消息转发失败
        void CustomizeController_TransmitFailed(ESPlus.Application.Information info)
        {
            if (info.InformationType == InformationTypes.Chat) //目前只保存离线的聊天消息
            {
                OfflineMessage msg = new OfflineMessage(info.SourceID, info.DestID, info.InformationType, info.Content);
                this.virtualDB.StoreOfflineMessage(msg);
                return;
            }
        }

        //发送离线消息给客户端
        public void SendOfflineMessage(string destUserID)
        {            
            List<OfflineMessage> list = this.virtualDB.PickupOfflineMessage(destUserID);
            if (list != null && list.Count > 0)
            {
                foreach (OfflineMessage msg in list)
                {
                    byte[] bMsg = CompactPropertySerializer.Default.Serialize<OfflineMessage>(msg);
                    this.rapidServerEngine.CustomizeController.Send(msg.DestUserID, InformationTypes.OfflineMessage, bMsg);
                }
            }

        }
    }
}
